package com.renshengjiwu.utils;

import com.alibaba.fastjson.JSON;
import com.renshengjiwu.web.dto.ServerInfo;
import org.beetl.core.GroupTemplate;
import org.beetl.ext.spring.BeetlGroupUtilConfiguration;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by xuzhike on 2016/1/16.
 */
public class BeetlSharedVarsUtil {
  public static void setupOnlineSharedVars(HttpServletRequest request) {
    String contextPath = request.getServletContext().getContextPath();
    ServerInfo serverInfo =  ServerInfo.getServerJSON(request);
    String serverInfoJSON =  JSON.toJSONString(serverInfo);
    BeetlGroupUtilConfiguration config = (BeetlGroupUtilConfiguration) SpringUtil.getBean("beetlConfig");
    if (config != null) {
      GroupTemplate group = config.getGroupTemplate();
      Map<String, Object> shared = new HashMap<String, Object>();
      shared.put("ctxPath", contextPath);
       shared.put("serverInfo", serverInfoJSON);
       String app = StrKit.isBlank(serverInfo.getServletContextPath())?"/"+serverInfo.getServletContextPath():"";
       shared.put("httpAppURL","http://"+serverInfo.getServerName()+":"+serverInfo.getServerPort()+app);
      // shared.put("wsAppURL","ws://"+serverInfo.getServerName()+":"+serverInfo.getServerPort()+app);
      group.setSharedVars(shared);
    }
  }

  public static void setupOnlineSharedVars(String key, Object value) {
    BeetlGroupUtilConfiguration config = (BeetlGroupUtilConfiguration) SpringUtil.getBean("beetlConfig");
    if (config != null) {
      GroupTemplate group = config.getGroupTemplate();
      Map<String, Object> shared = group.getSharedVars();
      shared.put(key, value);
    }
  }

}
